package br.brpv.silvestrin.conferencia.webservice;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.ksoap2.serialization.SoapObject;

import android.content.Context;
import br.brpv.silvestrin.conferencia.R;
import br.brpv.silvestrin.conferencia.helper.Compression;
import br.brpv.silvestrin.conferencia.helper.Encryption;
import br.brpv.silvestrin.conferencia.models.User;
import br.brpv.silvestrin.conferencia.webservice.WebserviceManager.WSRequestCompleteListener;

public class LoginWebservice extends Webservice implements
		WSRequestCompleteListener<SoapObject> {

	LoginwebserviceListener loginListener;

	public LoginWebservice(Context context,
			LoginwebserviceListener loginListener) {
		super(context);

		this.loginListener = loginListener;
	}

	public void selectUser(String user, String password) {

		WebserviceManager ws = new WebserviceManager(context,
				context.getString(R.string.wsmessage_selectinguser), this);

		try {
			String wlParametros = "" + "p_nome|varchar|" + user.toUpperCase()
					+ "||" + "^p_senha|varchar|" + Encryption.encrypt(password)
					+ "||";

			ws.execute(WebserviceManager.Method.F_GET_PACKAGE,
					"pkg_ger_usuarios.prc_seleciona_usuario", wlParametros);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void onTaskComplete(SoapObject result) {
		if (result == null) {
			loginListener.onSelectUserServerError();
		} else {

			String resultString = Compression.decompress(result.getProperty(0)
					.toString());
			System.out.println(resultString);

			loginListener.onSelectUser(parseUser(resultString));

		}

	}

	private User parseUser(String serverResult) {
		StringTokenizer row = new StringTokenizer(serverResult,
				Character.toString(ROW_BREAK_CHARACTER));
		// pula primeira linha
		row.nextToken();
		if (!row.hasMoreTokens())
			return null;
		else {

			ArrayList<String> tokens = new ArrayList<String>();
			String str = row.nextToken();

			while (str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
				tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
				str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
			}
			tokens.add(str);

			return new User(tokens.get(2), tokens.get(4));
		}
	}

	public interface LoginwebserviceListener {
		public void onSelectUser(User user);

		public void onSelectUserServerError();
	}
}
